/*
 * Copyright (c) 2018-2999 湖南洛云网络科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 */

package com.yami.shop.sys.multishop.controller;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.yami.shop.bean.enums.PositionType;
import com.yami.shop.common.annotation.SysLog;

import javax.validation.Valid;

import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.security.comment.model.UpdatePasswordDto;
import com.yami.shop.security.multishop.util.SecurityUtils;
import com.yami.shop.sys.comment.model.ShopEmployee;
import com.yami.shop.sys.comment.model.SysUser;
import com.yami.shop.sys.comment.service.ShopEmployeeService;
import com.yami.shop.sys.comment.service.ShopRoleService;
import com.yami.shop.sys.comment.service.SysRoleService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import lombok.AllArgsConstructor;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.common.util.PageParam;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 商家端用户
 * @author cl
 * @date 2021-03-01 17:42:09
 */
@RestController
@RequestMapping("/sys/shopEmployee" )
public class ShopEmployeeController {

    @Autowired
    private ShopEmployeeService shopEmployeeService;

    @Autowired
    private ShopRoleService shopRoleService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 分页查询
     * @param page 分页对象
     * @param shopEmployee 系统用户
     * @return 分页数据
     */
    @GetMapping("/page" )
    public ResponseEntity<IPage<ShopEmployee>> getShopEmployeePage(PageParam<ShopEmployee> page, ShopEmployee shopEmployee) {
        // 只显示店铺自己的管理员
        ShopEmployee employee = shopEmployeeService.getShopEmployeeById(SecurityUtils.getShopUser().getEmployeeId());
        PageParam<ShopEmployee> resPage = shopEmployeeService.page(page, new LambdaQueryWrapper<ShopEmployee>()
                .eq(ShopEmployee::getShopId,SecurityUtils.getShopUser().getShopId())
                .ne(!Objects.equals(0,employee.getType()),ShopEmployee::getType, PositionType.ADMIN.value())
                .like(StrUtil.isNotBlank(shopEmployee.getUsername()),ShopEmployee::getUsername,shopEmployee.getUsername()));
        return ResponseEntity.ok(resPage);
    }

    /**
     * 获取登录的用户信息
     */
    @GetMapping("/info")
    public ResponseEntity<ShopEmployee> info(){
        ShopEmployee employee = shopEmployeeService.getShopEmployeeById(SecurityUtils.getShopUser().getEmployeeId());
        if (Objects.isNull(employee)) {
            throw new YamiShopBindException("yami.shop.data.is.removed");
        }
        return ResponseEntity.ok(employee);
    }

    /**
     * 修改登录用户密码
     */
    @SysLog("商家端-修改密码")
    @PostMapping("/password")
    @ApiOperation(value="修改密码", notes="修改当前登陆用户的密码")
    public ResponseEntity<String> password(@RequestBody @Valid UpdatePasswordDto param){
        Long employeeId = SecurityUtils.getShopUser().getEmployeeId();
        ShopEmployee dbShopEmployee = shopEmployeeService.getShopEmployeeById(employeeId);
        if (!passwordEncoder.matches(param.getPassword(), dbShopEmployee.getPassword())) {
            // 原密码不正确
            return ResponseEntity.badRequest().body(I18nMessage.getMessage("yami.password.error"));
        }
        //新密码
        String newPassword = passwordEncoder.encode(param.getNewPassword());
//		更新密码
        shopEmployeeService.updatePasswordByEmployeeId(employeeId, newPassword);
        return ResponseEntity.ok().build();
    }


    /**
     * 通过id查询系统用户
     * @param employeeId id
     * @return 单个数据
     */
    @GetMapping("/info/{employeeId}" )
    @PreAuthorize("@pms.hasPermission('sys:shopEmployee:info')")
    public ResponseEntity<ShopEmployee> getById(@PathVariable("employeeId") Long employeeId) {
        ShopEmployee dbShopEmployee = shopEmployeeService.getShopEmployeeById(employeeId);
        dbShopEmployee.setUserId(null);
        //获取用户所属的角色列表
        List<Long> roleIdList = shopRoleService.listRoleIdByEmployeeId(employeeId);
        dbShopEmployee.setRoleIdList(roleIdList);
        return ResponseEntity.ok(dbShopEmployee);
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/shopEmployeeInfo")
    @PreAuthorize("@pms.hasPermission('sys:shopEmployee:info')")
    public ResponseEntity<ShopEmployee> shopEmployeeInfo(){
        ShopEmployee shopEmployee = shopEmployeeService.getShopEmployeeById(SecurityUtils.getShopUser().getEmployeeId());
        shopEmployee.setEmployeeId(null);
        shopEmployee.setPassword(null);
        return ResponseEntity.ok(shopEmployee);
    }

    /**
     * 新增系统用户
     * @param shopEmployee 系统用户
     * @return 是否新增成功
     */
    @PostMapping
    @PreAuthorize("@pms.hasPermission('sys:shopEmployee:save')" )
    public ResponseEntity<String> save(@RequestBody @Valid ShopEmployee shopEmployee) {
        String username = shopEmployee.getUsername();
        ShopEmployee dbEmployee = shopEmployeeService.getOne(new LambdaQueryWrapper<ShopEmployee>()
                .eq(ShopEmployee::getUsername, username));
        if (Objects.nonNull(dbEmployee)) {
            // 该用户已存在
            return ResponseEntity.badRequest().body(I18nMessage.getMessage("yami.sys.user.already"));
        }
        shopEmployee.setShopId(SecurityUtils.getShopUser().getShopId());
        shopEmployee.setCreateEmployeeId(SecurityUtils.getShopUser().getEmployeeId());
        shopEmployee.setType( PositionType.STAFF.value());
        shopEmployee.setPassword(passwordEncoder.encode(shopEmployee.getPassword()));
        shopEmployeeService.saveUserAndUserRole(shopEmployee);
        return ResponseEntity.ok().build();
    }

    /**
     * 修改系统用户
     * @param shopEmployee 系统用户
     * @return 是否修改成功
     */
    @PutMapping
    @PreAuthorize("@pms.hasPermission('sys:shopEmployee:update')" )
    public ResponseEntity<String> updateById(@RequestBody @Valid ShopEmployee shopEmployee) {
        String password = shopEmployee.getPassword();

        ShopEmployee dbEmployee = shopEmployeeService.getShopEmployeeById(shopEmployee.getEmployeeId());
        ShopEmployee dbEmployeeInfo = shopEmployeeService.getByUserName(dbEmployee.getUsername());
        if (Objects.equals( PositionType.ADMIN.value(),dbEmployee.getType())) {
            // 店铺超级管理员，不能在此处更改
            return ResponseEntity.badRequest().body(I18nMessage.getMessage("yami.shop.sys.super.user.no.modify"));
        }
        if (dbEmployeeInfo != null && !Objects.equals(dbEmployeeInfo.getEmployeeId(),shopEmployee.getEmployeeId())) {
            // 该用户已存在
            return ResponseEntity.badRequest().body(I18nMessage.getMessage("yami.sys.user.already"));
        }
        if (StrUtil.isBlank(password)) {
            shopEmployee.setPassword(null);
        }else {
            shopEmployee.setPassword(passwordEncoder.encode(password));
        }
        shopEmployeeService.updateUserAndUserRole(shopEmployee);
        return ResponseEntity.ok().build();
    }

    /**
     * 通过id删除系统用户
     * @return 是否删除成功
     */
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('sys:shopEmployee:delete')" )
    public ResponseEntity<String> removeById(@RequestBody Long[] employeeIds) {
        if (employeeIds.length == 0) {
            // 请选择需要删除的用户
            return ResponseEntity.badRequest().body(I18nMessage.getMessage("yami.sys.select.user"));
        }
        List<Long> ids = Lists.newArrayList(employeeIds).stream().distinct().collect(Collectors.toList());

        List<ShopEmployee> shopEmployees = shopEmployeeService.listByIds(ids);
        // 是否包含店铺超级管理员
        List<Integer> types = shopEmployees.stream().map(ShopEmployee::getType).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(types) && types.contains(PositionType.ADMIN.value())){
            // 系统管理员不能删除
            return ResponseEntity.badRequest().body(I18nMessage.getMessage("yami.sys.admin.error"));
        }
        if(ArrayUtil.contains(employeeIds, SecurityUtils.getShopUser().getEmployeeId())){
            // 当前用户不能删除
            return ResponseEntity.badRequest().body(I18nMessage.getMessage("yami.sys.delete.error"));
        }
        shopEmployeeService.removeByIds(Arrays.asList(employeeIds));
        return ResponseEntity.ok().build();
    }

}
